package com.example.websocket;


import com.example.controller.alarmbyMonitor;
import com.example.controller.cockpit.CockpitData;
import com.example.pojo.GuliException;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.text.ParseException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocketJSC/{userId}")
@Component
public class WebSocketServerJSC {
    static CockpitData cockpitData;

    @Autowired
    public void setRabbitAdmin(CockpitData cockpitData) {
        this.cockpitData = cockpitData;
    }


    static Log log = LogFactory.getLog(WebSocketServerJSC.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    //private static CopyOnWriteArraySet<WebSocketServer4> webSocketSetMap = new CopyOnWriteArraySet<WebSocketServer4>();

    private static Map<String, Session> webSocketSetMap = new ConcurrentHashMap<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //接受用户id
    private String userId;
    //用来判断  serialController.init();是否已经打开
    private static boolean isOpen = false;


    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) throws ParseException {


        webSocketSetMap.put(userId, session);

        this.userId = userId;
        CockpitData.userId = userId;
        cockpitData.JSC(userId);
        try {

        } catch (Exception e) {
            log.error("连接异常");
            throw new GuliException(500, "数据库数据错误");
        }


    }

    @OnClose
    public void onClose() {

        //LineChart.userId = "";
        //从set中删除
        webSocketSetMap.remove(this);
        //在线人数减一
        subOnlineCount();


        log.info("有连接关闭");
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到" + "的消息" + message);
        try {
            // LineChart.userId = this.userId;
        } catch (Exception e) {
            e.printStackTrace();
        }

        //

    }

    @OnError
    public void onError(Session session, Throwable err) {
        log.info("连接错误");
        err.printStackTrace();
    }


    public static void sendMessage(String message, String userId) {

        for (Session s : webSocketSetMap.values()) {
            try {
                //给前端发送数据
                if (s.equals(webSocketSetMap.get(userId))) {
                    s.getBasicRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public static synchronized void addOnlineCount() {
        WebSocketServerJSC.onlineCount++;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServerJSC.onlineCount--;
    }

}